<template>
    <div class="boxContentCss">
            <EdCreateCard :title="isUpdate ? '编辑巡检计划' : '新增巡检计划'">
                <template #back>
                    <div class="createBack" @click="$utilsSet.goBack($router)" >
                        <svg-icon icon-class="back" /> 返回
                    </div>
                </template>
                <el-form class="width-m25" :model="form"  ref="ruleForm" label-position='right' label-width="120px">
                    <el-row :gutter="20">
                        <el-col :span="6">
                            <el-form-item class="width-m25" label="项目名称" prop="villageId" :rules="$validate.validates({required:true,msg:'请选择项目名称'})">
                            <EdSelect v-model="form.villageId" :selectParams="villageNameParams" style="width: 100%;"  @emit-select-value="projectChange"></EdSelect>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item class="width-m25" label="巡检类型" prop="patrolType"  :rules="$validate.validates({required:true,msg:'请选择巡检类型'})">
                            <EdSelect v-model="form.patrolType" :selectParams="patrolTypeParams" style="width: 100%;" :formatter="setDicType" @emit-select-value="patrolTypeChange"></EdSelect>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item class="width-m25"  label="计划名称" prop="planName" :rules="$validate.validates({required:true,msg:'请选择计划名称'})">
                                <el-input class="flex-input"  v-model="form.planName" placeholder="请输入计划名称" maxlength="50"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="20" >
                        <el-col :span="12">
                            <el-form-item class="width-m25"  label="巡检点位" prop="planLocationDTOList" :rules="$validate.validates({required:true,msg:'请选择点位'})">
                                <template v-if="form.planLocationDTOList.length > 0">
                                    <div style="display: flex; flex-direction: row;align-items: end;width: 100%">
                                        <el-scrollbar class="scrollbar" style="width:70%,height:128px" v-if="form.planLocationDTOList.length > 0" >
                                            <div v-for="(item,index) in form.planLocationDTOList" :key="index" class="item">
                                                <span>{{item.name}}</span>
                                                <div @click="delPonit(index)"><i class="el-icon-close" style="cursor: pointer"></i></div>
                                            </div>
                                        </el-scrollbar>
                                    </div>
                                </template>
                                <template v-else>
                                    <el-button  @click="selectPoint()" class="ed-button ed_black-bottom">选择点位</el-button>
                                </template>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="20" v-if="form.planLocationDTOList.length > 0">
                        <el-col :span="12">
                            <el-form-item>
                                 <el-button  @click="selectPoint()" class="ed-button ed_black-bottom">选择点位</el-button>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="20" v-for="(item, index) in form.planDateDTOList" :key="index">
                        <el-col :span="6" v-if="index == 0">
                            <el-form-item label="时间" :prop="`planDateDTOList[${index}].type`" :rules="$validate.validates({required:true,msg:'请选择时间'})">
                                <EdSelect v-model="item.type" :selectParams="selecttime" style="width:100%"></EdSelect>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6" v-else>
                            <el-form-item >
                            </el-form-item>
                        </el-col>
                        <el-col :span="6" class="timeStyle">
                            <el-form-item :prop="`planDateDTOList[${index}].startTime`" :rules="$validate.validates({required:true,msg:'请选择时间'})">
                                <el-time-picker style="width:100%"
                                    is-range
                                    range-separator="至"
                                    v-model="item.startTime"
                                    value-format="HH:mm"
                                    start-placeholder="开始时间"
                                    end-placeholder="结束时间"
                                    format="HH:mm"
                                    @change="valiDateEenTime(index)">
                            </el-time-picker>
                            </el-form-item>
                        </el-col>
                        <el-col :span="3">
                            <el-button class="ed_button_delete ed_delete_bottom"  v-if="form.planDateDTOList.length > 1" type="info" @click="delTime(index)" icon="el-icon-delete" style="margin-top: 4px;"></el-button>
                            <el-button  @click="addTime" class="ed_button ed_black-bottom" icon="el-icon-plus" style="margin-top: 4px;"></el-button>
                        </el-col>
                   </el-row>
                    <el-row :gutter="20" >
                        <el-col :span="24">
                                <div class="projectButton">
                                    <el-button  type="info" @click="submit()" class="ed-button ed_black-bottom">提&nbsp;&nbsp;交</el-button>
                                    <el-button @click="$utilsSet.goBack($router),dialogVisible = false" class="ed-button ed_white_bottom">取&nbsp;&nbsp;消</el-button>
                                </div>
                        </el-col>
                    </el-row>
                </el-form>    
            </EdCreateCard>
            <EdDialog ref="dialogRef" v-if="showChoosePoint" title="请选择点位" @close-dialog="closeDialog" @save-dialog="saveDialog">
                <el-table
                    ref="multipleTable"
                    :data="tableData"
                    tooltip-effect="dark"
                    style="width: 100%"
                    height="300px"
                    @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55" align="center"></el-table-column>
                    <el-table-column label="全选" prop="locationName" >
                    </el-table-column>
                    <el-table-column>
                        <template slot="header" slot-scope="scope">
                            <el-input
                            v-model="queryPoint.locationName"
                            size="mini"
                            clearable
                            @blur="handleQuery"
                            @keyup.enter.native="handleQuery"
                            placeholder="输入关键字词"></el-input>
                        </template>
                    </el-table-column>
                </el-table>
            </EdDialog>

    </div>
</template>

<script>
    import EdDialog from 'src/components/EdDialog.vue'
    import EdSelect from 'src/components/EdSelect.vue'
    import EdCreateCard from 'src/components/EdCreateCard.vue'
    import { defineComponent } from 'vue'
    import {addRow,editRow,projectList,getId} from "./api.js";
    import {pointList,} from "../point/api"
    import {getDictByCode} from "src/api/dictionaries";
    export default defineComponent({
        name: "projectCreate",
        components: { EdCreateCard,EdSelect,EdDialog},
        data(){
            return{
                form:{
                   type:'',
                   villageName:'',
                   villageId:'',
                   patrolType:'',
                   patrolTypeName:'',
                   planName:'',
                   planLocationDTOList: [],
                   planDateDTOList: [
                       {type:'day',startTime:'', endTime:''}
                   ],
                },
                villageNameParams:{
                    placeholder:"请选择项目名称",
                    options: [],
                    props: {label:"label", value:"value"}
                },
                patrolTypeParams:{
                    placeholder:"请选择",
                    options: [],
                },
                selecttime:{
                    placeholder:"请选择",
                    options: [
                        {
                            label:'每天' ,
                            value:'day'
                        },
                    ],
                    props: {label:"label", value:"value"}
                },        
                showChoosePoint:false,
                queryPoint: {
                    page: 1,
                    pageSize: 99999,
                    locationName: '',
                    villageName:'',
                    villageId:''
                },
                isIndeterminate:false,
                checkAll:false,
                tableData: [],
                multipleSelection: [],
                isUpdate:false,
            }
        },
        created() {
            this.initDic()
        },
        activated(){
            if(this.$route.query.id){
                this.isUpdate=true;
                this.getId()
            }else{
                this.isUpdate = false
            }
            //  console.log('mounted')
        },
        deactivated() {
            this.form = {
                   type:'',
                   villageName:'',
                   villageId:'',
                   patrolType:'',
                   patrolTypeName:'',
                   planName:'',
                   planLocationDTOList: [],
                   planDateDTOList: [
                       {type:'day',startTime:'', endTime:''}
                   ],
            }
            this.multipleSelection = []
            this.$refs['ruleForm'].resetFields();
        },
        methods:{
            getId(){
                getId({id:this.$route.query.id}).then(response => {
                    if(response.success) {
                        this.form = {...response.data}
                        this.form.patrolType = response.data.patrolType.toString()
                        this.form.villageId = response.data.villageId.toString()
                        response.data.periodList.forEach(x=>{
                            if(x.startTime&&x.endTime){
                                let array = []
                                array.push(x.startTime)
                                array.push(x.endTime)
                                x.startTime = array
                            }
                        })
                        this.$set(this.form,'planDateDTOList',response.data.periodList)
                    }
                })
            },
            initDic(){
                projectList({page:1,pageSize:999999}).then(response => {
                    if(response.success) {
                        let options = response.data.records.map(x=>{return {label:x.villageName,value:x.villageId}})
                        this.villageNameParams.options=options
                    } 
                })
                // 获取字典值方式
                getDictByCode("patrolType").then(response => {
                    if(response.success) {
                        this.patrolTypeParams.options=response.data.items
                    }
                })
            },
            setDicType(row ,cloumn) {
                let options = this.patrolTypeParams.options.find(x => x.value == row.patrolType)
                return options.label
            }, 
            addTime() {
                this.form.planDateDTOList.push({type: 'day', startTime:'', endTime:''})
            },
            delTime(index) {
                this.form.planDateDTOList.splice(index, 1)
            },
            selectPoint(){
                if(!this.form.villageId) {
                    this.$message.warning({
                        message: '请先选择项目！',
                        duration: 2000,
                        center:true
                    });
                    return
                }
                this.handleQuery()
                this.showChoosePoint=true
                
            },
            closeDialog(){
                this.showChoosePoint=false
            },
            saveDialog(){
                 this.showChoosePoint=false
                 let ids = this.multipleSelection.map(x=>{return {id:x.id,name:x.locationName,installationSite:x.installationSite,url:x.url}})
                 this.form.planLocationDTOList = ids
            },
            handleCheckAllChange(){
              this.isIndeterminate = false
            },
            handleSelectionChange(val) {
                this.multipleSelection = val;
                
            },
            delPonit(index) {
                this.form.planLocationDTOList.splice(index, 1)
            },
            handleQuery() {
                this.queryPoint.villageId= this.form.villageId
                let options = this.villageNameParams.options.find(x=>x.value==this.queryPoint.villageId)
                this.form.villageName = options.label
                this.queryPoint.villageName= this.form.villageName
                pointList(this.queryPoint).then(response => {
                    if(response.success) {
                        this.tableData = response.data.records
                    }
                }).then(res=>{
                    this.toggleSelection()
                })
            },
            toggleSelection() {
                this.$nextTick(() => {
                    if (this.form.planLocationDTOList && this.form.planLocationDTOList.length > 0) {
                        // 找到选择的数据和列表相同的数据
                        let rows = this.tableData.filter(x => this.form.planLocationDTOList.some(item => item.id == x.id))
                        rows.forEach(row => {
                            this.$refs.multipleTable.toggleRowSelection(row)
                        })
                    } else {
                        if(this.$refs.multipleTable)
                        this.$refs.multipleTable.clearSelection()
                    }
                })
            },
            valiDateEenTime(index) {
                let planDate = this.form.planDateDTOList[index]
                if(planDate.startTime && planDate.endTime) {
                    if(planDate.startTime > planDate.endTime) {
                        this.$message.warning({
                            message: '结束时间不能小于开始时间',
                            duration: 2000,
                            center:true
                        });
                        planDate.endTime = ''
                    }
                }
            },
            submit(){
                this.$refs['ruleForm'].validate((valid)=>{
                    if(!valid){
                        return
                    }
                    this.form.planDateDTOList.forEach(item => {
                        if(item.startTime){
                          let start =item.startTime[0]
                          let end = item.startTime[1]
                          item.startTime = start
                          item.endTime = end
                        }
                    })
                    // 先判断是不是编辑按钮，如果是就调下面编辑的api
                    if(this.isUpdate){
                        editRow(this.form).then(response => {
                            if(response.success) {
                                this.$message.success({
                                    message: '编辑成功！',
                                    duration: 2000,
                                    center:true
                                });
                                this.$router.back()
                                
                            }
                        })
                    }else{
                        // 新增巡检计划确定时调的api
                        addRow(this.form).then(response => {
                                if(response.success) {
                                    this.$message.success({
                                        message: '新增计划成功！',
                                        duration: 2000,
                                        center:true
                                    });
                                    this.$router.back()
                                }
                            })
                        }
                    })
            },
            projectChange(row) {
                let option = this.villageNameParams.options.find(x=>x.value==row)
                this.handleQuery()
                this.form.planLocationDTOList=[]
                this.multipleSelection=[]
                return option ? option.label : ''
                
                
            },
            patrolTypeChange(row) {
                let option = this.patrolTypeParams.options.find(x=>x.value==row)
                this.form.patrolTypeName = option.label
            },
        },
        
    })
</script>

<style lang="scss" scoped>
.boxContentCss{
    position: relative;
    padding-bottom: 150px;
    .el-form{
        padding: 45px 45px 15px 15px;
    }
}
.projectButton{
    flex: 1;
    display: flex;
    justify-content: flex-start;
    margin-left: 120px;
}
.createBack{
    margin-right: 50px;
}
.time {
    .el-form-item__content {
        margin-left: 10px
    }
}
.checkboxPoint{
    display: flex;
    justify-content: space-between;
}
:deep .el-table .el-table__body-wrapper{
    &::-webkit-scrollbar-thumb{
        background-color: #C1C1C1;
        border-radius: 2px;
    }
}
.scrollbar {
    height: 150px;
    border: 1px solid #DCDFE6;
    border-radius: 2px;
    padding: 0 10px;
    width: 100%;
    .item {
        display: flex;
        align-content: center;
        justify-content: space-between;
        padding: 0 4px;
        border-radius: 2px;

        &:hover {
            background-color: bisque;
        }
    }
}
:deep .timeStyle .el-form-item__content{
    width: 100%;
    margin-left: 0 !important;
}
:deep .el-input__inner {
        border-radius: 8px;
}

</style>